<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\common\MyAgentController;
use App\Http\Controllers\Controller;

class LogController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex(Request $request)
    {
        $agentId = $request->cookie('agentId');
        $get['ag'] = $request->input('ag',$agentId);
        $get['eui'] = $request->input('eui','');
        $get['num'] = $request->input('num','');
        $get['genre'] = $request->input('genre','');
        /*开始时间*/
        $start = $request->input('start','');
        if($start == ''){
            $get['start'] = strtotime('2000-06-16 00:00:00');
        }else{
            $get['start'] = strtotime(str_replace('+',' ',$start));
        }
        /*结束时间*/
        $end = $request->input('end','');
        if($end == ''){
            $get['end'] = strtotime(date('Y-m-d',time()))+24*60*60-1;
        }else{
            $get['end'] = strtotime(str_replace('+',' ',$end));
        }
        /*代理商下拉菜单-----始*/
        //查询父级代理商path
        $path = DB::table('sa_agent') -> select('path') -> where(['id'=>$agentId]) -> first();
        $len = substr_count($path['path'],',');
        $agent = MyAgentController::allAgent($agentId);
        foreach ($agent as $k=>$v){
            $agent[$k]['agent_name'] = str_repeat('--',substr_count($v['path'],',')-$len)."<img src='/admin/images/company.png'>&nbsp;&nbsp;".$v['agent_name'];
        }
        /*代理商下拉菜单-----末*/
        // $agentId = 4;
        $data = DB::table('sa_log_msg')
            -> where('lg_agent_id','=',$get['ag'])
            -> where('lg_eui','like','%'.$get['eui'].'%')
            -> where('lg_num','like','%'.$get['num'].'%')
            -> whereBetween('lg_time',[$get['start'],$get['end']])
            -> where('lg_genre','like','%'.$get['genre'].'%')
            -> orderBy('lg_time', 'desc')
            -> paginate(1);
        return view('admin.log.index',['agent'=>$agent,'data' => $data,'request' =>$request->all(),'get'=>$get]);
    }

    public function getPages(Request $request)
    {
        $agentId = $request->cookie('agentId');
        $get['ag'] = $request->input('ag');
        $get['num'] = $request->input('num','');
        if(empty($get['ag'])) $get['ag'] =$agentId;
        $get['eui'] = $request->input('eui','');
        $get['genre'] = $request->input('genre','');
        /*开始时间*/
        $start = $request->input('start','');
        if($start == ''){
            $get['start'] = strtotime('2000-06-16 00:00:00');
        }else{
            $get['start'] = strtotime(str_replace('+',' ',$start));
        }
        /*结束时间*/
        $end = $request->input('end','');
        if($end == ''){
            $get['end'] = strtotime(date('Y-m-d',time()))+24*60*60-1;
        }else{
            $get['end'] = strtotime(str_replace('+',' ',$end));
        }
        $data = DB::table('sa_log_msg')
            -> where('lg_agent_id','=',$get['ag'])
            -> where('lg_eui','like','%'.$get['eui'].'%')
            -> where('lg_num','like','%'.$get['num'].'%')
            -> whereBetween('lg_time',[$get['start'],$get['end']])
            -> where('lg_genre','like','%'.$get['genre'].'%')
            -> orderBy('lg_time', 'desc')
            -> paginate(1);
        return view('admin.log.page_pro',['data' => $data,'request' =>$request->all(),'get'=>$get]);
    }
    public function getCreat(Request $request)
    {
        
        $sub = '';
        $agentId = $request->cookie('agentId');
        // $agentId = 4;
        // $Jstr = '{"hd":{"ver":"0","rdTk":"1234","pktp":0,"gwad":"T6CN470S0019"},"rxpk":{"time":"2017-05-30T17:54:50.188967Z","tmst":"1496138090","freq":472.700000,"datr":"SF8BW125","rssi":"-96.3","lsnr":"-1.3","chan":6,"mote":{"DevE":"FF0A000000000007","DevA":18119,"AppE":"BB02000000AB1112","fcnt":95,"fprt":1,"fmtp":2,"data":"gGQ=","datar":"0000"}},"action":"app_data"}';
        // 获取jsonp字符串
        $Jstr = $request -> get('Jstr');
        // 判断是否有值
        if($Jstr){
            // 转换成数组
            $message = json_decode($Jstr,true);
            $DevE = $message['rxpk']['mote']['DevE'];
            $App = $message['rxpk']['mote']['AppE'];
            $datar = $message['rxpk']['mote']['datar'];
            $row = DB::table('sa_room_detector as de')
                -> LeftJoin('sa_room as r','de.rd_r_id','=','r.r_id')
                -> LeftJoin('sa_building as b','de.rd_b_id','=','b.b_id')
                -> LeftJoin('sa_area as a','de.rd_a_id','=','a.a_id')
                -> select('de.rd_sd_eui','a.a_name','b.b_name','r.r_name','r.r_floor','de.rd_agent_id')
                -> where('de.rd_agent_id','=',$agentId)
                -> where('de.rd_sd_eui','=',$DevE)
                -> first();
            if($row)
            {
                // 时间
                $row['lg_time'] = date('Y-m-d H:i:s',$message['rxpk']['tmst']);
                $Lsnr = floatval($message['rxpk']['lsnr']);
                // 判断电量
                if($Lsnr >= 0)
                {
                    $row['lsnr'] = 3;
                }
                elseif($Lsnr < 0 && $Lsnr>=-10)
                {
                    $row['lsnr'] = 2;
                }
                elseif($Lsnr<-10)
                {
                    $row['lsnr'] = 1;
                }
                // dd($row);
                // 判断所属应用
                switch($App)
                {
                    case "BB02000000AB1111": // 烟感应用
                        $row['Type'] = '烟感';
                        $sub = self::Smoke($datar);
                        break;
                    case "0000000000000035": // 电气应用
                        $row['Type'] = '电气';
                        $sub = self::Electric($datar);
                        break;
                    case "BB02000000AB1112": // 呼救应用
                        $row['Type'] = '呼叫';
                        $sub = self::Call_help($datar);
                        break;
                    default:
                }
                $row['genre'] = $sub['genre'];
                $row['degree'] = $sub['degree'];
                echo json_encode($row);
        
        /*    "rd_sd_eui" => "FF0A000000000007"
            "a_name" => "河南全一科技"
            "b_name" => "绿地中心"
            "r_name" => "绿地中心东区办公室"
            "r_floor" => 13
            "rd_agent_id" => 1
            "time" => "1496138090"
            "lsnr" => 2
            "Type" => "电气"
            "genre" => "心跳5"
            "degree" => ""*/
            }else{
                echo '';
            }
        // dd($row);
        }else{
            echo '';
        }
    }

    /**
    *   烟感数据包解析
    *   string  $datar   接收烟感数据包 十六进制
    *   return  array    $status
    *   return  string   $status['degree']  温度
    *   return  string   $status['genre']   报警类型
    *
    */
    static function Smoke($datar)
    {
        $status = array();
        $sub = substr($datar,0,1);
        if($sub =='a')
        {
            // 温度 a2401fffe1
            $status['degree'] = hexdec(substr($datar,4,2));
            // 消息类型
            $make = substr($datar,1,1);
            if($make == '1')
            {
                $genre = decbin(substr($datar,3,1));
                // dd($genre);
                $mk = str_pad($genre,4,'0',STR_PAD_LEFT);
                if(substr($mk,0,1)==1)
                {
                    $status['genre'] = '火灾';
                }else{
                    if(substr($mk,3,1)=='1')
                    {
                        $status['genre'] = '温度';
                    }else{
                        if(substr($mk,1,1))
                        {
                            $status['genre'] = '故障';   
                        }else{
                            if(substr($mk,2,1)==1)
                            {
                                $status['genre'] = '欠压';
                            }else{
                                $status['genre'] = '';
                            }
                        }
                    }
                }
            }elseif($make == '2')
            {
                // 心跳
                $status['genre'] = "心跳";
            }
        }
        if($sub =='b')
        {
            $msg= array();
            // 温度 b2e000170000e1
            $status['degree'] = hexdec(substr($datar,6,2));
            // 消息类型
            $make = substr($datar,1,1);
            if($make == '1')
            {
                $status['genre'] = '';
                $arr = array('火灾','烟感故障','烟感欠压','温度','自检',7=>'防拆','失联','底座故障','底座欠压','其他故障');
                $mk = str_pad(decbin(substr($datar,3,1)),4,'0',STR_PAD_LEFT).str_pad(decbin(substr($datar,4,1)),4,'0',STR_PAD_LEFT).str_pad(decbin(substr($datar,5,1)),4,'0',STR_PAD_LEFT);
                for($i=strlen($mk)-1;$i>=0;$i--){
                    if($mk[$i]==1){
                        $status['genre'] = $arr[$i];
                    }
                }
            }elseif($make == '2')
            {
                // 心跳
                $status['genre'] = "心跳";
            }
        }
        return $status;
    }
    /**
    *   电气数据包解析
    *
    *
    */
    static function Electric($datar)
    {
        $status = array();
        $sub = str_replace('0','',substr($datar,22,6));
        if(empty($sub)){
            $status['genre'] = '心跳';
            $status['degree'] = '';
        }else{
            if(substr($datar,22,1))
            {
                switch(substr($datar,22,1))
                {
                    case '1':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,46,2));
                        break;
                    case '2':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,50,2));
                        break;
                    case '4':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,54,2));
                        break;
                    case '8':
                        $status['genre'] = '温度';
                        $status['degree'] = hexdec(substr($datar,58,2));
                        break;
                    default:
                        $status['genre'] = '心跳';
                        $status['degree'] = '';
                }
            }else{
                $status['genre'] = '心跳';
                $status['degree'] = '';
            }
        }
        return $status;
    }
    static function Call_help($datar)
    {
        $status['genre'] = '';
        $status['degree'] = '';
        $sub_f = substr($datar,0,1);
        if($sub_f == 0)
        {
            $sub = substr($datar,2,1);
            if($sub == 0)
            {
                $status['genre'] = '呼救';
            }
            if($sub == 8)
            {
                $status['genre'] = '紧急呼救';
            }
        }elseif($sub_f == 1){
           $status['genre'] = '心跳';
        }
        return $status;
        // return $sub_f;
    }
}
